/**
 * 
 */
package com.boshanam.application.tiles.init.config;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.tiles.TilesApplicationContext;
import org.apache.tiles.context.TilesRequestContextFactory;
import org.apache.tiles.definition.DefinitionsFactoryException;
import org.apache.tiles.factory.BasicTilesContainerFactory;

/**
 * @author Swetha
 * 
 */
public class AutoFindTilesContainerFactory extends BasicTilesContainerFactory {
    private final static Logger log = Logger.getLogger(AutoFindTilesContainerFactory.class.getName());
    
    @Override
    protected List<URL> getSourceURLs(TilesApplicationContext applicationContext,
	    TilesRequestContextFactory contextFactory) {
	List<URL> urls = new ArrayList<URL>();
	try {
		File webInfDir = new File("WEB-INF/defs/");
		log.log(Level.INFO, "Directory Selected for Tiles Definition files: " + webInfDir);
		String[] filesList = webInfDir.list();
		for(String file : filesList) {
			log.log(Level.INFO, "File Found: " + file);
			if(file.startsWith("tiles-") && file.endsWith(".xml")) {
				log.log(Level.INFO, "File Picked: "+file);
				urls.add(applicationContext.getResource("/WEB-INF/defs/" + file));
			}
		}
		log.log(Level.INFO, "Total Tiles Def Config List: " + urls);
	} catch (IOException e) {
	    throw new DefinitionsFactoryException("Cannot load definition URLs", e);
	}
	return urls;
    }
}
